package team.nmsg.ge.system.init;

import java.util.LinkedList;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import team.nmsg.ge.system.bean.SysBusinessLog;
import team.nmsg.ge.system.util.SysDBHelper;

/**
 * 
 * @author Guodeqi
 *
 */
public class SysBusiLogAdditThread extends Thread{

	private static Log logger = LogFactory.getLog( SysBusiLogAdditThread.class );
	
	private static SysBusiLogAdditThread logThread = new SysBusiLogAdditThread();
	
	public static SysBusiLogAdditThread getInstance(){
		return logThread;
	}
	
	private LinkedList<SysBusinessLog> logQueue = new LinkedList<SysBusinessLog>();
	private Session hsession = null;
	private boolean stopFlag = false;
	
	private SysBusiLogAdditThread(){
		super("SYS-BusinessLogAdditThread");
		start();
	}
	
	@Override
	public void run() {
		while(!stopFlag){
			try {
				SysBusinessLog toAdd = null;
				synchronized( logQueue ){
					if( logQueue.size()>0 ){
						toAdd = logQueue.removeFirst();
					}
					if( toAdd==null ){
						if( hsession != null ){
//							hsession.flush();
							hsession.close();
							hsession = null;
						}
						logQueue.wait();
					}
				}
				
				if( toAdd != null  ){
					if( hsession == null ){
						hsession = SysDBHelper.getHelper().openHSession();
					}
					hsession.save(toAdd);
				}
				
			} catch ( Exception e) {
				logger.error("" , e);
			}
			
		}
	}
	
	public void addBLog( SysBusinessLog log ){
		String ip = "";
		try {
			 ServletRequestAttributes attr = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
			HttpServletRequest request = attr.getRequest();
//			ip = request.getRemoteHost();
			ip = request.getRemoteAddr();
			log.setSrcIpAddress(ip);
		} catch (Exception e) {
		}
		synchronized (logQueue) {
			int size = logQueue.size();
			logQueue.add(log);
			if( size==0 ){
				logQueue.notifyAll();
			}
		}
	}
	
	public void stopBLogging(){
		stopFlag = true;
	}
	
}
